<?php
/**
 * Created by PhpStorm.
 * User: coolinmind
 * Date: 24/01/2019
 * Time: 12:02
 */

namespace App\Services\UCenter\UCenter;


use App\Models\Car\Car;
use App\Models\Car\CarDriver;
use App\Models\Cargo\Cargo;
use App\Models\Cargo\PhoneRecord;
use App\Models\Cargo\ViewRecord;
use App\Models\Cargo\WayBill;
use App\Models\Fund\FundAccount;
use App\Models\Fund\FundOptionLog;
use App\Models\UCenter\CompanyDriver;
use App\Models\Subscription\Subscription;
use App\Models\UCenter\Complain;
use App\Models\UCenter\Entrust;
use App\Models\User\User;
use App\Services\Fund\FundAccount\FundAccountLogic;
use App\Services\Setting\SettingIndex;
use App\Services\User\Traits\Password;
use Illuminate\Support\Facades\DB;

class WayBillLogic
{
    use Password;
    /**
     * 车主接单（形成运单）
     * @param $data
     * @return array
     */
    public function createPrivateWayBill($data)
    {
        $cargoInfo = Cargo::with('user')->where(['id' => $data['cargo_id']])->first();
        if (!$cargoInfo)
            return auto_failure($cargoInfo, '该货源不存在');
        if($cargoInfo['status'] == '已关闭') {
            return auto_failure($cargoInfo, '该货源已关闭');
        }elseif ($cargoInfo['status'] == '已接单'){
            return auto_failure($cargoInfo, '已被接单');
        }
        $newData = [
            'code' => str_random(6),
            'number' => $this->createWayBillNum(),
            'cargo_id' => $data['cargo_id'],
            'driver_id' => $data['user_id'],
            'phone' => $data['phone'],
            'owner_id' => $cargoInfo['user_id'],
            'price' => $cargoInfo['price'],
            'start_province_id' => $cargoInfo['start_province_id'],
            'start_city_id' => $cargoInfo['start_city_id'],
            'start_county_id' => $cargoInfo['start_county_id'],
            'end_province_id' => $cargoInfo['end_province_id'],
            'end_city_id' => $cargoInfo['end_province_id'],
            'end_county_id' => $cargoInfo['end_county_id'],
            'volume' => $cargoInfo['volume'],
            'start_addr_detail' => $cargoInfo['start_addr_detail'],
            'start_addr' => $cargoInfo['start_addr'],
            'end_addr' => $cargoInfo['end_addr'],
            'end_addr_detail' => $cargoInfo['end_addr_detail'],
            'receiver_name' => $cargoInfo['receiver_name'],
            'receiver_phone' => $cargoInfo['receiver_phone'],
            'car_type' => $cargoInfo['car_type'],
            'weight' => $cargoInfo['weight'],
            'car_lenght' => $cargoInfo['car_lenght'],
            'loading_time' => $cargoInfo['loading_time'],
            'type' => $cargoInfo['type'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        DB::beginTransaction();
        try {
            //改变货源状态
            $cargoInfo->status = 2;
            $cargoInfo->save();
            $car = Car::where('number','=', $data['car_card'])->where('user_id','=',$data['user_id'])->first();
//            if ($car->is_busy == 1) {
//                DB::rollBack();
//                return auto_failure(null, '该车辆已占用');
//            }
            $car->is_busy = 1;
            $car->save();
            $newData['car_card'] = $car->number;
            $newData['driver'] = $car->owner;
            $res = WayBill::insertGetId($newData);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return auto_failure($e->getMessage(), '接单失败');
        }
        return auto_success($res, '接单成功');
    }

    /**
     * 公司接单（形成运单）
     * @param $data
     * @return array
     */
    public function createCompanyWayBill($data)
    {
        //判断是否是委托单
        $entrust = Entrust::where('driver','=',$data['driver'])->where('car_card','=',$data['car_card'])->where('status','=',1)->first();
        if(!empty($entrust)){
            $company_id = $entrust->company_id;
            $entrust_status = 1;
        DB::beginTransaction();
            try {
                Entrust::where('id','=',$entrust->id)->update(['status'=>3]);
                Car::where('user_id','=',$company_id)->where('number','=',$data['car_card'])->update(['is_del'=>1]);
                //DB::commit();
            } catch (\Exception $e) {
                //DB::rollBack();
                return auto_failure($e->getMessage(), '接单失败');
            }
        }
        //正常公司下的司机接单
        $companyDriver = CompanyDriver::where('driver_id','=',$data['driver_id'])->first();
        if(!empty($companyDriver)){
            $company_id = $companyDriver->company_id;
        }
        $cargoInfo = Cargo::with('user')->where(['id' => $data['cargo_id']])->first();
        if (!$cargoInfo)
            return auto_failure($cargoInfo, '该货源不存在');
        if($cargoInfo['status'] == '已关闭') {
            return auto_failure($cargoInfo, '该货源已关闭');
        }elseif ($cargoInfo['status'] == '已接单'){
            return auto_failure($cargoInfo, '已被接单');
        }
        $newData = [
            'code' => str_random(6),
            'number' => $this->createWayBillNum(),
            'cargo_id' => $data['cargo_id'],
            'driver_id' => $data['driver_id'],
            'driver' => $data['driver'],
            'car_card' => $data['car_card'],
            'phone' => $data['phone'],
            'assit_driver' => $data['driver'],
            'assit_phone' => $data['assit_phone'],
            'owner_id' => $cargoInfo['user_id'],
            'price' => $cargoInfo['price'],
            'start_province_id' => $cargoInfo['start_province_id'],
            'start_city_id' => $cargoInfo['start_city_id'],
            'start_county_id' => $cargoInfo['start_county_id'],
            'end_province_id' => $cargoInfo['end_province_id'],
            'end_city_id' => $cargoInfo['end_province_id'],
            'end_county_id' => $cargoInfo['end_county_id'],
            'volume' => $cargoInfo['volume'],
            'start_addr' => $cargoInfo['start_addr'],
            'end_addr' => $cargoInfo['end_addr'],
            'receiver_name' => $cargoInfo['receiver_name'],
            'receiver_phone' => $cargoInfo['receiver_phone'],
            'car_type' => $cargoInfo['car_type'],
            'weight' => $cargoInfo['weight'],
            'car_lenght' => $cargoInfo['car_lenght'],
            'type' => $cargoInfo['type'],
            'loading_time' => $cargoInfo['loading_time'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'company_id' => !empty($company_id) ? $company_id : $data['user_id'],
            'entrust_status' =>!empty($entrust_status) ? $entrust_status : 0,
        ];
        //DB::beginTransaction();
        try {
                $res = WayBill::insertGetId($newData);
                //添加委托运单id
                Entrust::where('id','=',$entrust->id)->update(['waybill_id'=>$res]);
                //改变货源状态
                $cargoInfo->status = 2;
                $cargoInfo->save();
                $car = Car::where('number','=', $data['car_card'])->where('user_id','=',$data['user_id'])->first();
                $car->is_busy = 1;
                $car->save();
                DB::commit();
        } catch (\Exception $e) {
            return auto_failure($e->getMessage(), '接单失败');
        }
        return auto_success($res, '接单成功');
    }

    /**
     * 生成订单号
     * @return string
     */
    private function createWayBillNum()
    {
        $num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        return $num;
    }

    /**
     * 根据id获取运单详情
     * @param $data
     * @return array
     */
    public function getWayBillDetail($data)
    {
        if (in_array(163, explode(',', $data['role_ids']))) {
            $withArr = ['comments', 'comments.commentContents', 'driver'];
        }else{
            $withArr = ['comments', 'comments.commentContents', 'owner'];
        }
        $info = WayBill::with($withArr)->find($data['id'])->toArray();
        if(!$info)
            return auto_failure($info, '获取失败');

        //车主、货主按钮、运单状态结果处理
        $info = $this->wayBillBtn($info);
        return auto_success($info, '获取成功');
    }

    /**
     * 车主、货主按钮、运单状态结果处理
     * @param $info
     * @return array
     */
    private function wayBillBtn($info)
    {
        $ownerBtn = [
            'action' => '',
            'text' => '',
            'is_main_display' => true, // 主按钮是否显示
            'is_complain_display' => false, // 投诉按钮是否显示
            'is_waybill_status_display' => false, // 运单状态是否显示
            'is_step_display' => false, // 步进条是否显示
            'is_map_display' => false, //运单地图是否显示
            'is_driver_display' => false, // 接单司机是否显示
            'is_cargo_display' => false, // 获物信息是否显示
            'is_comment_display' => false, // 评价是否显示
            'is_loading_display' => false, // 装货信息是否显示
            'is_unload_display' => false, // 卸货信息是否显示
            'is_pay_display' => false, // 支付运费按钮是否显示
            'is_callback_display' => false, // 拍照回执是否显示
            'is_code_display' => false, // 提货码是否显示
        ];
        $ownerStatus = '';
        switch ($info['status']) {
            case 0:
                $ownerBtn['is_main_display'] = false;
                $ownerBtn['is_waybill_status_display'] = true;
                $ownerBtn['is_unload_display'] = true;
                $ownerBtn['is_cargo_display'] = true;
                $ownerBtn['is_map_display'] = true;
                $ownerStatus = '已取消';
                break;
            case 1:
                if ($info['owner_pay_status'] == 0) {
                    $ownerBtn['action'] = 'cancel';
                    $ownerBtn['text'] = '我要取消';
                    $ownerBtn['is_pay_display'] = true;
                    $ownerBtn['is_step_display'] = true;
                    $ownerBtn['is_map_display'] = true;
                    $ownerBtn['is_cargo_display'] = true;
                    $ownerBtn['is_driver_display'] = true;
                    $ownerStatus = '待付款';
                }else{
                    $ownerBtn['action'] = 'arrive';
                    $ownerBtn['text'] = '确认到达';
                    $ownerBtn['is_pay_display'] = true;
                    $ownerBtn['is_step_display'] = true;
                    $ownerBtn['is_map_display'] = true;
                    $ownerBtn['is_cargo_display'] = true;
                    $ownerBtn['is_driver_display'] = true;
                    $ownerBtn['is_waybill_status_display'] = true;
                    $ownerBtn['is_callback_display'] = true;
                    $ownerBtn['is_unload_display'] = true;
                    $ownerBtn['is_code_display'] = true;
                    $ownerStatus = '待取货';
                }
                break;
            case 2:
                if ($info['owner_arrive'] == 0) {
                    $ownerBtn['action'] = 'arrive';
                    $ownerBtn['text'] = '确认到达';
                    $ownerBtn['is_step_display'] = true;
                    $ownerBtn['is_map_display'] = true;
                    $ownerBtn['is_cargo_display'] = true;
                    $ownerBtn['is_driver_display'] = true;
                    $ownerBtn['is_loading_display'] = true;
                    if($info['is_unload'] == 1)
                        $ownerBtn['is_callback_display'] = true;
                    $ownerStatus = '运输中';
                }
                break;
            case 3:
                if ($info['owner_arrive']) {
                    if ($info['is_owner_comment'] == 0) {
                        $ownerBtn['action'] = 'comment';
                        $ownerBtn['text'] = '发表评价';
                        $ownerBtn['is_step_display'] = true;
                        $ownerBtn['is_map_display'] = true;
                        $ownerBtn['is_driver_display'] = true;
                        $ownerBtn['is_comment_display'] = true;
                        $ownerBtn['is_waybill_status_display'] = true;
                        $ownerBtn['is_main_display'] = false;
                        $ownerStatus = '待评价';
                    }
                }else{
                    $ownerBtn['action'] = 'comment';
                    $ownerBtn['text'] = '发表评价';
                    $ownerBtn['is_step_display'] = true;
                    $ownerBtn['is_map_display'] = true;
                    $ownerBtn['is_driver_display'] = true;
                    $ownerBtn['is_comment_display'] = true;
                    $ownerBtn['is_waybill_status_display'] = true;
                    $ownerBtn['is_code_display'] = true;
                    $ownerBtn['is_unload_display'] = true;
                    $ownerBtn['is_cargo_display'] = true;
                    $ownerBtn['is_callback_display'] = true;
                    $ownerStatus = '运输中';
                }
                break;
            case 4:
                $ownerStatus = '已完成';
                break;
            case 5:
                $ownerBtn['action'] = 'complaint';
                $ownerBtn['text'] = '投诉';
                $ownerBtn['is_step_display'] = true;
                $ownerBtn['is_map_display'] = true;
                $ownerBtn['is_cargo_display'] = true;
                $ownerBtn['is_driver_display'] = true;
                $ownerBtn['is_loading_display'] = true;
                $ownerStatus = '已投诉';
                break;
            case 6:
                $ownerBtn['action'] = 'complaint';
                $ownerBtn['text'] = '投诉';
                $ownerBtn['is_step_display'] = true;
                $ownerBtn['is_map_display'] = true;
                $ownerBtn['is_cargo_display'] = true;
                $ownerBtn['is_driver_display'] = true;
                $ownerBtn['is_loading_display'] = true;
                $ownerStatus = '已回复';
                break;
        }

        $driverBtn = [
            'action' => '',
            'text' => '',
            'is_main_display' => true, // 主按钮是否显示
            'is_complain_display' => true, // 投诉按钮是否显示
            'is_input_code_display' => false, // 输入提货码功能是否显示
            'is_waybill_status_display' => true, // 运单状态是否显示
            'is_step_display' => true, // 步进条是否显示
            'is_map_display' => true, //运单地图是否显示
            'is_driver_display' => true, // 接单司机是否显示
            'is_cargo_display' => true, // 获物信息是否显示
            'is_comment_display' => false, // 评价是否显示
            'is_loading_display' => true, // 装货信息是否显示
            'is_callback_display' => false, // 拍照回执是否显示
        ];
        $driverStatus = '';
        // 按钮判断
        switch ($info['status']) {
            case 0:
                $driverStatus = '已取消';
                break;
            case 1:
                if ($info['owner_pay_status'] == 0) {
                    $driverBtn['is_main_display'] = false;
                    $driverBtn['is_cargo_display'] = false;
                    $driverBtn['is_comment_display'] = false;
                    $driverBtn['is_loading_display'] = false;
                    $driverStatus = '待付款';
                } elseif ($info['owner_pay_status'] == 1) {
                    if ($info['driver_pay_status'] == 0) {
                        $driverBtn['is_main_display'] = true;
                        $driverBtn['action'] = 'pay_deposit';
                        $driverBtn['text'] = '支付保证金';
                    } else {
                        $driverBtn['is_main_display'] = true;
                        $driverBtn['action'] = 'loading';
                        $driverBtn['text'] = '我已装货';
                    }
                    $driverStatus = '待取货';
                }
                break;
            case 2:
                if ($info['dstatus'] == 1) {
                    //判断是否确认到达
                    if ($info['driver_arrive'] == 0) {
                        $driverBtn['is_main_display'] = true;
                        $driverBtn['action'] = 'arrive';
                        $driverBtn['text'] = '到达目的地';
                        $driverStatus = '运输中';
                    } elseif($info['driver_arrive'] == 1) {
                        //判断是否卸货
                        if ($info['is_unload'] == 0) {
                            $driverBtn['is_main_display'] = true;
                            $driverBtn['action'] = 'complete';
                            $driverBtn['text'] = '完成卸货';
                            $driverBtn['is_input_code_display'] = true;
                            $driverBtn['is_callback_display'] = true;
                            $driverStatus = '已到达';
                        }else{
                            if ($info['is_driver_comment'] == 0) {
                                $driverBtn['is_main_display'] = true;
                                $driverBtn['is_comment_display'] = true;
                                $driverBtn['is_loading_display'] = false;
                                $driverBtn['action'] = 'comment';
                                $driverBtn['text'] = '发表评价';
                                $driverStatus = '待评价';
                            }else{
                                $driverBtn['is_main_display'] = false;
                                $driverBtn['is_loading_display'] = false;
                                if ($info['is_owner_comment'] == 0) {
                                    $driverStatus = '待货主评价';
                                }
                            }
                        }
                    }
                }
                break;
            case 3:
                if ($info['is_driver_comment'] == 0) {
                    $driverBtn['is_main_display'] = true;
                    $driverBtn['is_comment_display'] = true;
                    $driverBtn['is_loading_display'] = false;
                    $driverBtn['action'] = 'comment';
                    $driverBtn['text'] = '发表评价';
                    $driverStatus = '待评价';
                }else{
                    $driverBtn['is_main_display'] = false;
                    $driverBtn['is_loading_display'] = false;
                    if ($info['is_owner_comment'] == 0) {
                        $driverStatus = '待货主评价';
                    }
                }
                break;
            case 4:
                $driverStatus = '已完成';
                break;
            case 5:
                $driverStatus = '已投诉';
                break;
            case 6:

                break;
        }
        $info['driver_btn'] = $driverBtn;
        $info['owner_btn'] = $ownerBtn;
        $info['driver_status_text'] = $driverStatus;
        $info['owner_status_text'] = $ownerStatus;
        return $info;
    }

    /**
     * 根据user_id获取车辆与司机
     * @param $data
     * @return array
     * @throws \App\Exceptions\RequestFailException
     */
    public function getCompanyCarAndDriver($data)
    {
        $car = Car::where('user_id', '=', $data['user_id'])->where('is_del',0)->get();
        return auto_success($car, '获取成功');
    }

    /**
     * 添加订阅路线
     * @param $data
     */
    public function addSubscription($data)
    {
        try {
            $res = Subscription::insert($data);
            return $res ?
                auto_success($res, '添加成功') :
                auto_failure($res, '添加失败');
        } catch (\Exception $e) {
            return auto_failure($e->getMessage());
        }
    }

    /**
     * 获取订阅列表
     * @param $data
     * @return array
     */
    public function getSubList($data)
    {
        try {
            $list = Subscription::where(['user_id' => $data['user_id']])->paginate(10, null, null, $data['page'])->toArray();
            foreach($list['data'] as $k=>$v){
                $list['data'][$k]['count'] = Subscription::from('subscriptions as s')->join('cargos as c',function($join){
                    $join->on('s.start_city_id','=','c.start_city_id')
                    ->on('s.end_city_id','=','c.end_city_id');
                })->where('s.start_city_id',$v['start_city_id'])
                    ->where('s.end_city_id',$v['end_city_id'])->where('c.status',1)->count();
            }
            return auto_return_page($list, '获取列表成功');
        } catch (\Exception $e) {
            return auto_failure($e->getMessage(), '获取列表失败');
        }
    }

    /**
     * 根据id删除订单列表
     * @param $data
     * @return array
     */
    public function delSubById($data)
    {
        try {
            $subMod = Subscription::where(['user_id' => $data['user_id'], 'id' => $data['id']])->first();
            if(!$subMod)
                return auto_failure($subMod, '该数据不存在');
            $res = $subMod->delete();
            return $res ?
                auto_success($res, '删除成功') :
                auto_failure($res, '删除失败');
        } catch (\Exception $e) {
            return auto_failure($e->getMessage(), '删除失败');
        }
    }

    /**
     * 根据user_id获取个人信息与车辆
     * @param $data
     * @return array
     * @throws \App\Exceptions\RequestFailException
     */
    public function getPrivateAndCar($data)
    {
        $driver = User::where('id', '=', $data['user_id'])->get();
        $car = Car::where('user_id', '=', $data['user_id'])->get();
        if (!empty($driver)) {
            $driver = $driver->toArray();
        }
        if (!empty($car)) {
            $car = $car->toArray();
        }
        $res['driver'] = $driver;
        $res['car'] = $car;
        return auto_success($res, '获取成功');
    }

    /**
     * 货主运单列表
     * @return array
     */
    public function wayBillOwnerList($data){
        if($data['type']==1) {
            $waybill = WayBill::with('driver')
                ->where('owner_id','=',$data['user_id'])
                ->get()
                ->toArray();
        }else if($data['type']==2){
            $waybill = WayBill::with('driver')
                ->where('owner_id','=',$data['user_id'])
                ->where('status','=',1)
                ->get()
                ->toArray();
        }else{
            $waybill = WayBill::with('driver')
                ->where('owner_id','=',$data['user_id'])
                ->where('status','=',3)
                ->get()
                ->toArray();
        }
        /**
         * 运单状态判断
         */
        $waybill = $this->ownerWayBillStatus($waybill);

        return auto_success($waybill,'获取成功');
    }

    /**
     * 货主运单状态判断
     * @param $waybill
     */
    private function ownerWayBillStatus($waybill)
    {
        foreach ($waybill as $k => &$v) {
            $ownerStatus = '';
            switch ($v['status']) {
                case 0:
                    $ownerStatus = '已取消';
                    break;
                case 1:
                    if ($v['owner_pay_status'] == 0) {
                        $ownerStatus = '待付款';
                    } elseif ($v['owner_pay_status'] == 1) {
                        $ownerStatus = '待取货';
                    }
                    break;
                case 2:
                    if ($v['dstatus'] == 1) {
                        $ownerStatus = '运输中';
                    }
                    break;
                case 3:
                    if ($v['is_owner_comment'] == 0) {
                        $ownerStatus = '待评价';
                    }
                    break;
                case 4:
                    $ownerStatus = '已完成';
                    break;
                case 5:
                    $ownerStatus = '已投诉';
                    break;
                case 6:

                    break;
            }
            $v['owner_status_text'] = $ownerStatus;
        }
        return $waybill;
    }

    //创建委托单
    public function createEntrust($data){
        DB::beginTransaction();
        try {
            //只能有一个正在进行的委托
            $driver_id = $data['user_id'];
            $entrust = Entrust::where('user_id',$driver_id)->where('status',1)->first();
            if(!is_null($entrust)){
                return auto_failure($entrust,'已有发布的委托');
            }
            //检查是否绑定公司
            $company = CompanyDriver::where('driver_id','=',$driver_id)->where('status',2)->first();
            if(empty($company)){
                return auto_failure($company,'还未绑定公司');
            }
            //检查该用户绑定的车辆是否合法
            $car = Car::where('number','=',$data['car_card'])->where('user_id','=',$driver_id)->where('status','=',1)->where('is_del',0)->first();
            if(empty($car)){
                return auto_failure($car,'还未绑定车辆或未审核通过');
            }
            $data['status'] = 1;
            $data['company_id'] = $company->company_id;
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['updated_at'] = date('Y-m-d H:i:s');
            $data['plate_type'] = $car->plate_type;
            //生成委托数据
            Entrust::insert($data);
            //添加车辆到公司
            $car = $car->toArray();
            $companyCar = Car::where('number','=',$data['car_card'])->where('user_id','=',$company->company_id)->where('status','=',1)->where('is_del',0)->first();
            if(!is_null($companyCar)){
                return auto_failure($companyCar,'该公司已有此车辆');
            }
            $newCar['user_id'] = $company->company_id;
            $newCar['plate_type'] = $car['plate_type'];
            $newCar['number'] = $car['number'];
            $newCar['driving_license'] = $car['driving_license'];
            $newCar['car_type'] = $car['car_type'];
            $newCar['car_length'] = $car['car_length'];
            $newCar['weight'] = $car['weight'];
            $newCar['carriage_num'] = $car['carriage_num'];
            $newCar['certificate'] = $car['certificate'];
            $newCar['volume'] = $car['volume'];
            $newCar['carrage_length'] = $car['carrage_length'];
            $newCar['register_date'] = $car['register_date'];
            $newCar['car_brand'] = $car['car_brand'];
            $newCar['identification_code'] = $car['identification_code'];
            $newCar['engine'] = $car['engine'];
            $newCar['engine_num'] = $car['engine_num'];
            $newCar['car_axle'] = $car['car_axle'];
            $newCar['axle'] = $car['axle'];
            $newCar['owner'] = $car['owner'];
            $newCar['status'] = $car['status'];
            $newCar['created_at'] = date('Y-m-d H:i:s');
            $newCar['updated_at'] = date('Y-m-d H:i:s');
            $res = Car::insertGetId($newCar);
            //添加车辆与用户的关系
            $carDriver['car_id'] = $res;
            $carDriver['driver_id'] = $driver_id;
            $carDriver['company_id'] = $company->id;
            $carDriver['status'] = 1;
            $carDriver['created_at'] = date('Y-m-d H:i:s');
            $carDriver['updated_at'] = date('Y-m-d H:i:s');
            CarDriver::insert($carDriver);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getMessage();
        }
        return auto_success($res ,'添加成功');
    }

    //取消运单
    public function cancelWayBill($data){
        $waybill = WayBill::where('id','=',$data['waybill_id'])->first();
        $owner_id = $waybill->owner_id;
        /*$driver_id = $waybill->driver_id;
        $waybill_id = $waybill->id;*/
        $cargo_id = $waybill->cargo_id;
        //是否是货主本人取消运单
        if($owner_id <> $data['user_id']){
            return auto_failure(false,'您无权取消该运单');
        }
        //是否重复取消运单
        if($waybill->status == 0){
            return auto_failure(false,'该运单已被取消，请勿重复操作');
        }
        //若货主车主付款 不能取消运单
        if($waybill->owner_pay_status == 1 || $waybill->driver_pay_status == 1 ){
            return auto_failure(false,'已有一方付款，该运单无法取消');
        }
        //若货主未付款 退还货主保证金
        //货主保证金对应货物ID
        if($waybill->owner_pay_status == 0){
            $_where['user_id'] = $owner_id;
            $_where['waybill_id'] = $cargo_id;
            $fundLog = FundOptionLog::where($_where)->first();
            $price = ltrim($fundLog->money,'-');
            //$payBack =  $this->payBack($owner_id,$price,$data['create_ip']);
            DB::beginTransaction();
            try {
                $this->payBack($owner_id, $price, $data['create_ip'], 'deposit', '退还保证金');
                DB::commit();
            }catch (\Exception $e){
                return auto_failure($e->getMessage(),'数据库异常退款失败');
            }
        }
        //若货主付款且车主未付款 退还车主保证金
        /*if($waybill->owner_pay_status == 1 && $waybill->driver_pay_status == 0){
            $_where['user_id'] = $driver_id;
            $_where['waybill_id'] = $waybill_id;
            $fundLog = FundOptionLog::where($_where)->first();
            $price = $fundLog->money;
            $payBack = $this->payBack($driver_id,$price,$data['create_ip']);
        }*/

//        if($payBack != 200){
//            return auto_failure(false,'取消退款失败');
//        }
        $res = WayBill::where('id','=',$data['waybill_id'])->update(['status'=>0]);
        if($res){
            return auto_success($res,'取消成功');
        }else{
            return auto_failure($res,'取消失败');
        }
    }

    //车主运单列表
    public function companyWayBillList($data){
        if($data['type']==1) {
            $waybill = WayBill::with('owner')
                ->where('driver_id','=',$data['user_id'])
                ->orWhere('company_id','=',$data['user_id'])
                ->get();
        }else if($data['type']==2){
            $waybill = WayBill::with('owner')
                ->where('driver_id','=',$data['user_id'])
                ->where('entrust_status','=',1)
                ->get();
        }else{
            $waybill = WayBill::with('owner')
                ->where('driver_id','=',$data['user_id'])
                ->Where('company_id','<>',0)
                ->get();

        }
        if(!empty($waybill)){
            $waybill = $waybill->toArray();
        }
        // 运单状态判断
        $waybill = $this->driverWayBillStatus($waybill);
        return auto_success($waybill,'获取成功');
    }

    /**
     * 车主运单列表状态判断
     * @param $waybill
     * @return mixed
     */
    private function driverWayBillStatus($waybill)
    {
        foreach ($waybill as $k => &$v) {
            $driverStatus = '';
            switch ($v['status']) {
                case 0:
                    $driverStatus = '已取消';
                    break;
                case 1:
                    if ($v['owner_pay_status'] == 0) {
                        $driverStatus = '待付款';
                    } elseif ($v['owner_pay_status'] == 1) {
                        $driverStatus = '待取货';
                    }
                    break;
                case 2:
                    if ($v['dstatus'] == 1) {
                        $driverStatus = '运输中';
                    }
                    break;
                case 3:
                    if ($v['is_driver_comment'] == 0) {
                        $driverStatus = '待评价';
                    }else{
                        if($v['is_owner_comment'] == 0)
                        $driverStatus = '待货主评价';
                    }
                    break;
                case 4:
                    $driverStatus = '已完成';
                    break;
                case 5:
                    $driverStatus = '已投诉';
                    break;
                case 6:

                    break;
            }
            $v['driver_status_text'] = $driverStatus;
        }
        return $waybill;
    }

    //取消委托
    public function cancelEntrust($data){
        try {
            $res = Entrust::where('id', '=', $data['id'])->first();
            $res->status = 2;
            $res->save();
            Car::where('user_id', '=', $res->company_id)->where('number', '=', $res->car_card)->delete();
        }catch(\Exception $e){
            return auto_failure($res,$e->getMessage());
        }
        if($res){
            return auto_success($res,'取消成功');
        }else{
            return auto_failure($res,'取消失败');
        }
    }

    //委托详情
    public function entrustDetail($data){
        $res = Entrust::where('id','=',$data['id'])->get();
        if($res){
            return auto_success($res,'获取成功');
        }else{
            return auto_failure($res,'获取失败');
        }
    }

    //修改委托
    public function updateEntrust($data){
        $data['updated_at'] = date('Y-m-d H:i:s');
        $res = Entrust::where('id','=',$data['id'])->update($data);
        if($res){
            return auto_success($res,'修改成功');
        }else{
            return auto_failure($res,'修改失败');
        }
    }

    //委托列表
    public function entrustList($data){
        if($data['type'] == 1){
            $res = Entrust::with('wayBill','car')->where('user_id','=',$data['user_id'])->orWhere('company_id','=',$data['user_id'])->get();
        }elseif ($data['type'] == 2){
            $res = Entrust::with('wayBill','car')->where('user_id','=',$data['user_id'])->where('status','=',1)->orWhere('company_id','=',$data['user_id'])->where('status','=',1)->get();
        }else{
            $res = Entrust::with('wayBill','car')->where('user_id','=',$data['user_id'])->where('status','=',3)->orWhere('company_id','=',$data['user_id'])->where('status','=',3)->get();
        }
        if($res){
            return auto_success($res,'返回成功');
        }else{
            return auto_failure($res,'返回失败');
        }
    }

    //修改运单
    public function updateWayBill($data){
        $data['updated_at'] = date('Y-m-d H:i:s');
        $res = WayBill::where('id','=',$data['id'])->update($data);
        if($res){
            return auto_success($res,'修改成功');
        }else{
            return auto_failure($res,'修改失败');
        }
    }

    //举报投诉
    public function createComplain($data){
        //转换图片格式
        $image1 = $data['upload1'];
        $image2 = $data['upload2'];
        $image3 = $data['upload3'];
        if (!empty($image1)) {
            $res1 = $this->base64ToImg($image1);
            if($res1['status'] != SUCCESS_STATUS) {
                return auto_failure($res1, '上传失败');
            }
            $data['upload1'] = $res1['res']['path'];
        }
        if (!empty($image2)) {
            $res2 = $this->base64ToImg($image2);
            if($res2['status'] != SUCCESS_STATUS) {
                return auto_failure($res2, '上传失败');
            }
            $data['upload2'] = $res2['res']['path'];
        }
        if (!empty($image3)) {
            $res3 = $this->base64ToImg($image3);
            if($res3['status'] != SUCCESS_STATUS) {
                return auto_failure($res3, '上传失败');
            }
            $data['upload3'] = $res3['res']['path'];
        }
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $res = Complain::insert($data);
        WayBill::where('number','=',$data['number'])->update(['status'=>5]);
        if($res){
            return auto_success($res,'举报成功');
        }else{
            return auto_failure($res,'举报失败');
        }
    }
    /**
     * 图片上传
     * @param $image
     * @return array
     */
    private function base64ToImg($image, $dirName = 'images')
    {
        $imageName = "25220_".date("His",time())."_".rand(1111,9999).'.png';
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }

        $path = "/uploads/".$dirName."/".date("Ymd",time());
        if (!is_dir('./'.$path)){ //判断目录是否存在 不存在就创建
            mkdir('./'.$path,0777,true);
        }
        $imageSrc=  $path."/". $imageName;  //图片名字

        $r = file_put_contents(ROOT_PATH ."public/".$imageSrc, base64_decode($image));//返回的是字节数
        return $r ?
            auto_success(['path' => $imageSrc]):
            auto_failure($r);
    }
    //举报详情
    public function complainDetail($data){
        $res = Complain::with('waybill')->where('number','=',$data['number'])->first();
        if($res){
            return auto_success($res,'获取成功');
        }else{
            return auto_failure($res,'该运单未投诉');
        }
    }

    //用户是否同意投诉处理结果
    public function complainDeal($data){
        $complain = Complain::where('id','=',$data['id'])->first();
        $deposit = SettingIndex::SettingCategory()->getSelection(['action' => 'deposit']);
        $ownerDeposit = $deposit['ownerDeposit'][0]-$complain->owner_cost;
        $driverDeposit = $deposit['ownerDeposit'][0]-$complain->driver_cost;
        $number = $complain->number;
        $waybill = WayBill::where('number','=',$number)->first();
        if(is_null($waybill)){
            return auto_failure($waybill,'没有此运单');
        }
        if($data['result'] == 1){
            if($waybill->owner_pay_status == 0 || $waybill->driver_pay_status ==0){
                WayBill::where('number','=',$number)->update(['status'=>1]);
            }else{
                WayBill::where('number','=',$number)->update(['status'=>2]);
            }
        }else{
            //取消订单
            if($waybill->owner_pay_status == 0 && $waybill->driver_pay_status == 0){
                WayBill::where('number','=',$number)->update(['status' => 0]);
            }else{
                $owner_id = $waybill->owner_id;
                $driver_id = $waybill->driver_id;
                $price = $waybill->price;
                DB::beginTransaction();
                try {
                    if ($waybill->driver_pay_status == 1) {
                        $this->payBack($driver_id, $driverDeposit, $data['create_ip'], 'deposit', '退还保证金');
                    }
                    if ($waybill->owner_pay_status == 1) {
                        $this->payBack($owner_id, $ownerDeposit, $data['create_ip'], 'deposit', '退还保证金');
                        $this->payBack($owner_id, $price, $data['create_ip'], 'payment', '退还运费');
                    }
                    DB::commit();
                }catch (\Exception $e){
                    return auto_failure($e->getMessage(),'数据库异常退款失败');
                }
                WayBill::where('number','=',$number)->update(['status' => 0]);
            }
        }
        $res = Complain::where('id','=',$data['id'])->update(['status'=>$data['status']]);
        if($res){
            return auto_success($res,'操作成功');
        }else{
            return auto_failure($res,'操作失败');
        }
    }

    /**
     * 取消订单退钱
     * @param $data
     */
    public function payBack($user_id,$price ='',$create_ip,$type,$remark)
    {
        $fundMod = FundAccount::where(['user_id' => $user_id])->first();
        $cash = $fundMod->cash;
        $total = $fundMod->total;
        $expend = $fundMod->expend;
        $deposit = $fundMod->deposit;
        $freeze = $fundMod->freeze;
        //DB::beginTransaction();
        //try {
            //修改用户资金
            if($type == 'deposit'){
                $fundMod->cash = bcadd($cash, $price);
                $fundMod->total = bcadd($total, $price);
                $fundMod->expend = bcsub($expend, $price);
                $fundMod->deposit = bcsub($deposit, $price);
            }else if($type == 'payment'){
                $fundMod->cash = bcadd($cash, $price);
                $fundMod->total = bcadd($total, $price);
               // $fundMod->expend = bcsub($expend, $price);
                $fundMod->freeze = bcsub($freeze, $price);
            }
            //添加资金日志
            $logData = [
                'user_id' => $user_id,
                'type' => $type,
                'money' => '+'.$price,
                'total' => $fundMod->total,
                'income' => $fundMod->income,
                'expend' => $fundMod->expend,
                'cash' => $fundMod->cash,
                'freeze' => $fundMod->freeze,
                'remark' => $remark,
                'user_info' => '{}',
                'opposite_info' => '{}',
                'create_ip' => $create_ip,
                'update_ip' => $create_ip,
                'create_time' => NOW,
                'update_time' => NOW
            ];
            $r1 = $fundMod->save();
            $r3 = FundOptionLog::insert($logData);
//            if($r1 && $r3){
//                DB::commit();
//                return 200;
//            }
//        } catch (\Exception $e) {
//            //DB::rollBack();
//            return $e->getMessage();
//        }
    }

    //确定装车
    public function truckLoading($data){
        if(in_array(163, explode(',', $data['role_ids']))){
            $waybill = WayBill::where('id','=',$data['id'])->first();
            $waybill->ostatus = 1;
            $waybill->status = 2;
            $waybill->save();
            $code = $waybill->code;
            $phone = $waybill->phone;
            //发送短信
        }else{
            $res = WayBill::where('id','=',$data['id'])->update(['dstatus'=>1, 'status' => 2]);
        }
        if($res){
            return auto_success($res,'操作成功');
        }else{
            return auto_failure($res,'操作失败');
        }
    }

    //完成卸货
    public function truckUnload($data){
        $waybill = WayBill::where('id','=',$data['id'])->first();
        $car_card = $waybill->car_card;
        $user_id = $waybill->driver_id;
        if($waybill->code != $data['code']){
            return auto_failure([],'验证码错误');
        }
        $waybill->upload1 = $data['upload1'];
        $waybill->upload2 = $data['upload2'];
        $waybill->upload3 = $data['upload3'];
        $waybill->is_unload = 1;
        $res = $waybill->save();
        if(!$res){
            $other = WayBill::where('car_card','=',$car_card)->where('driver_id',$user_id)->where('id','<>',$data['id'])->whereIn('status',[1,2])->first();
            if(is_null($other)){
                Car::where('number','=',$car_card)->where('user_id','=',$user_id)->update(['is_busy'=>0]);
            }
            return auto_failure([],'操作失败');
        }
        return auto_success($res,'操作成功');
    }

    /**
     * 运单支付
     * @param $data
     */
    public function pay($data)
    {
        //验证用户支付密码
        $info = User::select('pay_password','pay_salt')->where(['id' => $data['user_id']])->first()->toArray();
        if(!$info){
            return verify_err(null, '没有相关用户信息');
        }else if($info['pay_password'] === ''){
            return verify_err(null, '您还没有设置支付密码');
        }
        $check = $this->_checkPayPassword($data['pay_password'], $info);
        if(!$check){
            return verify_err(null, '支付密码错误');
        }
        $waybillMod = WayBill::where(['id' => $data['id'], 'owner_id' => $data['user_id']])->first();
        if(!$waybillMod)
            return auto_failure(null, '该运单不存在');
        if($waybillMod->owner_pay_status == 1)
            return auto_failure(null, '该运单已支付');
        $price = $waybillMod->price;
        $fundMod = FundAccount::where(['user_id' => $data['user_id']])->first();
        $cash = $fundMod->cash;
        // 判断余额是否充足
        $checkRes = bccomp($cash, $price);

        if(!$checkRes == -1)
            return auto_failure(null, '余额不足');

        DB::beginTransaction();
        try {
            //修改用户资金
            $fundMod->cash = bcsub($cash, $price);
            $fundMod->total = bcsub($fundMod->total, $price);
           // $fundMod->expend = bcadd($fundMod->expend, $price);
            $fundMod->freeze = bcadd($fundMod->freeze, $price);

            //修改订单状态
            $waybillMod->owner_pay_status = 1;

            //添加资金日志
            $logData = [
                'user_id' => $data['user_id'],
                'waybill_id' => $waybillMod->id,
                'type' => 'payment',
                'money' => '-'.$price,
                'total' => $fundMod->total,
                'income' => $fundMod->income,
                'expend' => $fundMod->expend,
                'cash' => $fundMod->cash,
                'freeze' => $fundMod->freeze,
                'remark' => '冻结运费',
                'user_info' => '{}',
                'opposite_info' => '{}',
                'create_ip' => $data['create_ip'],
                'update_ip' => $data['create_ip'],
                'create_time' => NOW,
                'update_time' => NOW
            ];

            $r1 = $fundMod->save();
            $r2 = $waybillMod->save();
            $r3 = FundOptionLog::insert($logData);
            if($r1 && $r2 && $r3){
                DB::commit();
                return auto_success(true, '支付成功');
            }else{
                return auto_failure(false, '支付失败');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return auto_failure($e->getMessage(), '数据库异常');
        }
    }

    //确认到达
    public function arrive($data)
    {
        //修改运单状态
        if(in_array(164, explode(',', $data['role_ids']))){
            $waybill = WayBill::where('id','=',$data['id'])->first();
            $user_id = $waybill->driver_id;
            User::where('id','=',$user_id)->increment('receive_num');
            $res = WayBill::where('id','=',$data['id'])->update(['driver_arrive'=>1]);
        }else{
            $res = WayBill::where('id','=',$data['id'])->update(['owner_arrive'=>1]);
        }
        $waybill = WayBill::where('id','=',$data['id'])->first();
        $owner_id = $waybill->owner_id;
        $driver_id = $waybill->driver_id;
        $waybill_id = $waybill->id;
        $cargo_id = $waybill->cargo_id;
        $price = $waybill->price;
        if($res){
            if ($waybill->driver_arrive == 0 || $waybill->owner_arrive == 0 ) {
                return auto_success($res,'确认成功,请等待对方确认');
            }
        }else{
            return auto_failure($res,'确认失败');
        }
        //判断是否为委托单，运费支付给司机或公司
        if($waybill->entrust_status == 1){
            $fundMod = FundAccount::where(['user_id' => $driver_id])->first();
            $user_id = $driver_id;
        }else{
            $fundMod = FundAccount::where(['user_id' => $waybill->company_id])->first();
            $user_id = $waybill->company_id;
        }
        //双方都确认到达后，运费打入车主账户 并添加资金记录 货主减少运费 并添加资金记录 退还双方保证金 并添加资金记录
        DB::beginTransaction();
        try {
            //修改车主资金
            $fundMod->cash = bcadd($fundMod->cash, $price);
            $fundMod->total = bcadd($fundMod->total, $price);
            $fundMod->income = bcadd($fundMod->expend, $price);

            //添加资金日志
            $logData = [
                'user_id' => $user_id,
                'type' => 'payment',
                'money' => $price,
                'total' => $fundMod->total,
                'income' => $fundMod->income,
                'expend' => $fundMod->expend,
                'cash' => $fundMod->cash,
                'freeze' => $fundMod->freeze,
                'remark' => '获得运费',
                'user_info' => '{}',
                'opposite_info' => '{}',
                'create_ip' => $data['create_ip'],
                'update_ip' => $data['create_ip'],
                'create_time' => NOW,
                'update_time' => NOW
            ];
            $r1 = $fundMod->save();
            $r2 = FundOptionLog::insert($logData);
            //修改货主资金
            $ownerFund = FundAccount::where(['user_id' => $owner_id])->first();
            $ownerFund->freeze = bcsub($ownerFund->freeze, $price);
            $ownerFund->expend = bcadd($ownerFund->expend, $price);

            //添加资金日志
            $logData = [
                'user_id' => $owner_id,
                'type' => 'payment',
                'money' => $price,
                'total' => $ownerFund->total,
                'income' => $ownerFund->income,
                'expend' => $ownerFund->expend,
                'cash' => $ownerFund->cash,
                'freeze' => $ownerFund->freeze,
                'remark' => '付出运费',
                'user_info' => '{}',
                'opposite_info' => '{}',
                'create_ip' => $data['create_ip'],
                'update_ip' => $data['create_ip'],
                'create_time' => NOW,
                'update_time' => NOW
            ];
            $r1 = $ownerFund->save();
            $r2 = FundOptionLog::insert($logData);
            // 退还车主保证金
            $_where2['user_id'] = $driver_id;
            $_where2['waybill_id'] = $waybill_id;
            $_where2['type'] = 'deposit';
            $fundLog2 = FundOptionLog::where($_where2)->first();
            $price = ltrim($fundLog2->money,'-');
            $this->payBack($driver_id,$price,$data['create_ip'],'deposit', '退还保证金');
            // 退还货主保证金
            $_where1['user_id'] = $owner_id;
            $_where1['waybill_id'] = $cargo_id;
            $_where1['type'] = 'deposit';
            $fundLog1 = FundOptionLog::where($_where1)->first();
            $price1 = ltrim($fundLog1->money,'-');
            $this->payBack($owner_id,$price1,$data['create_ip'],'deposit', '退还保证金');

            //if($r1 && $r2){
            DB::commit();
            return auto_success(true, '确认成功');
//            }else{
//                return auto_failure(false, '确认失败');
//            }
        } catch (\Exception $e) {
            //DB::rollBack();
            return auto_failure($e->getMessage(), '数据库异常');
        }
    }


    /**
     * 后台运单列表
     * @return array
     */
    public function waybillList($data)
    {
        $query = WayBill::join('user', 'waybills.owner_id', '=', 'user.id')
            ->select('user.name as owner_name', 'waybills.*');
        if($data['keywords']){
            $keyword = $data['keywords'];
            $query->where(function ($query) use ($keyword) {
                $query->where('waybills.number','like',"%".$keyword."%")->orWhere('waybills.code','like',"%".$keyword."%")->orWhere('user.name','like',"%".$keyword."%");
            });
        }
        $list = $query->orderBy('id','desc')->paginate(10);
        return auto_success($list,'获取成功');
    }

    /**
     * 后台运单详情
     * @return array
     */
    public function waybillInfo($data)
    {
        $_where['waybills.id'] = $data['id'];
        $info = WayBill::join('user', 'waybills.owner_id', '=', 'user.id')
            ->select('user.name as owner_name', 'waybills.*')
            ->where($_where)
            ->orderBy('id','desc')
            ->first();
        return auto_success($info,'获取成功');
    }

    /**
     * 车主支付保证金
     * @param $data
     */
    public function payDeposit($data)
    {
        $waybillMod = WayBill::where(['id' => $data['id']])->first();
        if(!$waybillMod)
            return auto_failure(null, '该运单不存在');
        if($waybillMod['driver_pay_status'])
            return auto_failure(null, '您已支付过保证金');
        $deposit = SettingIndex::SettingCategory()->getSelection(['action' => 'deposit']);
        // 准备数据
        $payPreData = [
            'user_id' => $data['user_id'],
            'deposit' => $deposit['driverDeposit'][0],
            'pay_pass' => $data['pay_password'],
            'pay_type' => 'balance',
            'create_ip' => $data['create_ip'],
            'waybill_id' => $data['id']
        ];
        $payRes = (new FundAccountLogic())->payDeposit($payPreData);
        if ($payRes['status'] == SUCCESS_STATUS) {
            $waybillMod->driver_pay_status = 1;
            $res = $waybillMod->save();
            return $res ?
                auto_success($res, '支付成功') :
                auto_failure(null, '支付失败');
        }else{
            return auto_failure($payRes, $payRes['msg']);
        }
    }

    /**
     * 委托统计
     * @param $data
     * @return array
     * @throws \App\Exceptions\RequestFailException
     */
    public function entrustStatistics($data){
        $count1 = Entrust::where('company_id',$data['user_id'])->where('status',1)->count();
        $count2 = Entrust::where('company_id',$data['user_id'])->where('status',2)->count();
        $count3 = Entrust::where('company_id',$data['user_id'])->where('status',3)->count();
        $query = Entrust::with('wayBill','car');
        !empty($data['start_time']) && $query->where('start_time','>',$data['start_time']);
        !empty($data['end_time']) && $query->where('end_time','<',$data['end_time']);
        !empty($data['driver']) && $query->where('driver',$data['driver']);
        !empty($data['car_card']) && $query->where('car_card',$data['car_card']);
        if($data['type'] == 1){
            $query->where('status',1);
        }else if($data['type'] == 2){
            $query->where('status',2);
        }else{
            $query->where('status',3);
        }
        $res = $query->paginate(10);
        return auto_success([$count1,$count2,$count3,$res],'成功返回数据');
    }

    //根据车牌号查找对应的司机
    public function companyByNumber($data){
        $waybill = WayBill::where('car_card',$data['number'])->whereIn('status',[1,2])->first();
        if(!is_null($waybill)){
            return auto_success(['type'=>1,$waybill],'返回成功');
        }
        $car = Car::where('number',$data['number'])->where('user_id',$data['user_id'])->where('is_del',0)->first();
        $carDriver = CarDriver::with('driver')->where('car_id',$car->id)->get();
        return auto_success(['type'=>2,$carDriver],'返回成功');
    }

    //委托拒绝接单
    public function entrustRefuse($data){
        DB::beginTransaction();
        try {
            $waybill = WayBill::where('id', $data['id'])->first();
            $waybill->status = 0;
            $waybill->save();
            $entrust = Entrust::where('waybill_id', $data['id'])->first();
            $entrust->status = 2;
            $entrust->save();
            $car_card = $entrust->car_card;
            $user_id = $entrust->company_id;
            Car::where('number',$car_card)->where('user_id',$user_id)->delete();
            Cargo::where('id',$waybill->cargo_id)->update(['status'=>1]);
            DB::commit();
            return auto_success($waybill,'拒绝成功');
        }catch (\Exception $e){
            return auto_failure($e->getMessage(),'操作失败');
        }
    }

    //通话记录
    public function createRecord($data){
        $data['created_at'] = date('Y-m-d');
        if($data['type'] == 1){
            unset($data['type']);
            $res = PhoneRecord::insert($data);
        }else{
            unset($data['type']);
            $res = ViewRecord::insert($data);
        }
        if($res){
            return auto_success($res,'添加成功');
        }
        return auto_failure($res,'添加失败');
    }

    //记录列表
    public function recordList($data){
        if($data['type'] == 1){
            $res = PhoneRecord::with('cargo','cargo.user')->where('user_id',$data['user_id'])->get();
        }else{
            $res = ViewRecord::with('cargo','cargo.user')->where('user_id',$data['user_id'])->get();
        }
        return auto_success($res,'返回成功');
    }

    //清空记录
    public function deleteRecord($data){
        PhoneRecord::where('user_id',$data['user_id'])->delete();
        ViewRecord::where('user_id',$data['user_id'])->delete();
        return auto_success('ok','清空成功');
    }

}
